//
//  JHUserAccount.swift
//  Weibo_SwiftDemo
//
//  Created by gjh on 2021/1/9.
//

import UIKit

private let accountFile = "useraccount.json"
// 用户账户信息
class JHUserAccount: NSObject {

    /// 访问令牌
    @objc var access_token: String? // = "2.00KXfZwB33BqyB586d7c866dHchaME"
    /// 用户代号
    @objc var uid: String?
    /// access_token的生命周期,时间是秒数
    /// 开发者是 5 年
    /// 使用者是 3 天
    @objc var expires_in: TimeInterval = 0 {
        didSet {
            expiresDate = Date(timeIntervalSinceNow: expires_in)
        }
    }
    
    /// 过期时间也得处理
    @objc var expiresDate: Date?
    /// 用户昵称
    var screen_name: String?
    /// 用户头像地址(大图),180*180
    var avatar_large: String?
    
    override var description: String {
        return yy_modelDescription()
    }
    
    
    /// 构造函数
    override init() {
        super.init()
        
        // 从磁盘加载保存的文件-字典
        // 加载磁盘文件到二进制数据,如果失败直接返回
        guard let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first?.appending("/\(accountFile)"),
              let data = NSData(contentsOfFile: path),
              let dict = try? JSONSerialization.jsonObject(with: data as Data, options: []) as? [String: AnyObject] else {
            return
        }
        // 使用字典设置属性
//        yy_modelSet(with: dict)
        
        // 测试过期日期
//        expiresDate = Date(timeIntervalSinceNow: -3600 * 24)
//        print(expiresDate)
        
        // 判断 token 是否过期
        if expiresDate?.compare(Date()) != .orderedDescending {
            print("账户过期")
            // 清空 token
            access_token = nil
            uid = nil
            // 删除账户文件
            try? FileManager.default.removeItem(atPath: path)
        }
        print("账户正常\(self)")
    }
    
    /// 1.偏好设置; 2.沙盒- 归档/plist/json; 3.数据库; 4.钥匙串访问(需要使用框架-SSKeyChain)
    func saveAccount() {
        // 1.模型转字典
        var dict = self.yy_modelToJSONObject() as? [String: AnyObject] ?? [:]
        
        // 删除expires_in值
        dict.removeValue(forKey: "expires_in")
        // 2.字典序列化成 data
        guard let data = try? JSONSerialization.data(withJSONObject: dict, options: []) else {
            return
        }
        let filePath = ((NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).first)! as String).appending("/\(accountFile)")
        // 3.写入磁盘
        (data as NSData).write(toFile: filePath, atomically: true)
        print("用户账户保存成功\(filePath)")
    }
}
